package org.jsets.fastboot.persistent.support;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;

import org.jsets.fastboot.persistent.IPageRequest;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.SharedString;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;

/**
 * 
 * Entity 对象查询器
 * <br>
 * 改进自：com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
 * 
 * <br>
 */
@SuppressWarnings("serial")
public class Querier<T> extends AbstractWrapper<T, String, Querier<T>> implements Query<Querier<T>, T, String> {

    /**
     * 查询字段
     */
    private final SharedString sqlSelect = new SharedString();
    
    private BaseMapper<T> baseMapper;
    protected Page<T> page;

    public Querier() {
        this(null);
    }

    public Querier(T entity) {
        super.setEntity(entity);
        super.initNeed();
    }

    public Querier(T entity, String... columns) {
        super.setEntity(entity);
        super.initNeed();
        this.select(columns);
    }
    
    /**
     * 非对外公开的构造方法,只用于生产嵌套 sql
     *
     * @param entityClass 本不应该需要的
     */
    private Querier(T entity, Class<T> entityClass, AtomicInteger paramNameSeq,
                         Map<String, Object> paramNameValuePairs, MergeSegments mergeSegments,
                         SharedString lastSql, SharedString sqlComment, SharedString sqlFirst) {
        super.setEntity(entity);
        super.setEntityClass(entityClass);
        this.paramNameSeq = paramNameSeq;
        this.paramNameValuePairs = paramNameValuePairs;
        this.expression = mergeSegments;
        this.lastSql = lastSql;
        this.sqlComment = sqlComment;
        this.sqlFirst = sqlFirst;
    }

    @Override
    public Querier<T> select(String... columns) {
        if (ArrayUtils.isNotEmpty(columns)) {
            this.sqlSelect.setStringValue(String.join(StringPool.COMMA, columns));
        }
        return typedThis;
    }

    @Override
    public Querier<T> select(Class<T> entityClass, Predicate<TableFieldInfo> predicate) {
        super.setEntityClass(entityClass);
        this.sqlSelect.setStringValue(TableInfoHelper.getTableInfo(getEntityClass()).chooseSelect(predicate));
        return typedThis;
    }

    @Override
    public String getSqlSelect() {
        return sqlSelect.getStringValue();
    }

    /**
     * 用于生成嵌套 sql
     * <p>
     * 故 sqlSelect 不向下传递
     * </p>
     */
    @Override
    protected Querier<T> instance() {
        return new Querier<>(getEntity(), getEntityClass(), paramNameSeq, paramNameValuePairs, new MergeSegments(),
            SharedString.emptyString(), SharedString.emptyString(), SharedString.emptyString());
    }

    @Override
    public void clear() {
        super.clear();
        sqlSelect.toNull();
    }
    
    public void setBaseMapper(BaseMapper<T> baseMapper) {
		this.baseMapper = baseMapper;
	}
    
	private synchronized <E extends IPage<T>> E getOrCreatePage() {
		if(this.page == null) {
			this.page = new Page<T>();
		}
		return (E)this.page;
	}
    
	
	public Querier<T> setCurrentPage(Integer currentPage) {
		getOrCreatePage().setCurrent(currentPage);
		return typedThis;
	}

	public Querier<T> setPageSize(Integer pageSize) {
		getOrCreatePage().setSize(pageSize);
		return typedThis;
	}
	
	public Querier<T> setPageCriteria(IPageRequest pageRequest) {
		getOrCreatePage().setCurrent(pageRequest.getCurrent());
		getOrCreatePage().setSize(pageRequest.getSize());
		return typedThis;
	}
	
	/**
     * <p>
     * 查询一条记录
     * </p>
     * 
     * @return T
     * 
	 * 
	 */
    public T selectOne() {
    	return this.baseMapper.selectOne(this);
    }
    
	/**
     * <p>
     * 查询一条记录
     * </p>
     * 
     * @return T
     */
    public Optional<T> findOne() {
    	return Optional.ofNullable(this.baseMapper.selectOne(this));
    }
    
    /**
     * <p>
     * 根据 Wrapper 条件，查询总记录数
     * </p>
     * 
     * @return int
     */
    public int selectCount() {
    	return SqlHelper.retCount(baseMapper.selectCount(this));
    }
    
    /**
     * <p>
     * 查询列表
     * </p>
     * 
     * @return List<T>
     */
    public List<T> selectList(){
    	return baseMapper.selectList(this);
    }
    
    /**
     * <p>
     * 翻页查询
     * </p>
     *
     * @return
     */ 
    public <E extends IPage<T>> E selectPage(E page){
    	Objects.requireNonNull(page);
    	
        E ipage = baseMapper.selectPage(page, this);
        return ipage;
    }
    
    /**
     * <p>
     * 翻页查询
     * </p>
     *
     * @return
     */ 
    public <E extends IPage<T>> E selectPage(){
        E ipage = baseMapper.selectPage(this.getOrCreatePage(), this);
        return ipage;
    }
    
    
    /**
     * 如果 val 为null则不加入查询条件
     * <br>
     * 如果 val 为字符串，为空串也不加入查询条件
     * @param column 列名称
     * @param val 值
     * @return QueryActuator<T>
     */
    public Querier<T> eqIfNecessary(String column, Object val) {
    	if(this.isNecessary(val)) {
    		this.eq(column, val);
    	}
    	return typedThis;
    }
    
    /**
     * 如果 val 为null则不加入查询条件
     * <br>
     * 如果 val 为字符串，为空串也不加入查询条件
     * @param column 列名称
     * @param val 值
     * @return QueryActuator<T>
     */
    public Querier<T> likeIfNecessary(String column, Object val) {
    	if(this.isNecessary(val)) {
    		this.like(column, val);
    	}
    	return typedThis;
    }
    
    /**
     * 如果 val 为null则不加入查询条件
     * <br>
     * 如果 val 为字符串，为空串也不加入查询条件
     * @param column 列名称
     * @param val 值
     * @return QueryActuator<T>
     */
    public Querier<T> geIfNecessary(String column, Object val) {
    	if(this.isNecessary(val)) {
    		this.ge(column, val);
    	}
    	return typedThis;
    }
    
    /**
     * 如果 val 为null则不加入查询条件
     * <br>
     * 如果 val 为字符串，为空串也不加入查询条件
     * @param column 列名称
     * @param val 值
     * @return QueryActuator<T>
     */
    public Querier<T> leIfNecessary(String column, Object val) {
    	if(this.isNecessary(val)) {
    		this.le(column, val);
    	}
    	return typedThis;
    }
    
    private boolean isNecessary(Object val) {
    	if(null==val) {
    		return false;
    	}
    	
    	if(val instanceof String) {
    		String str = (String)val;
    		if("".equals(str)) {
    			return false;
    		}
    	}
    	
    	return true;
    }
    
}